[[...path]].page.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, isServer, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import mongoose from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  17. import { PageComment } from '~/components/PageComment';
  18. // import { useTranslation } from '~/i18n';
  19. import { CommentEditorLazyRenderer } from '~/components/PageComment/CommentEditorLazyRenderer';
  20. import { PageContentFooter } from '~/components/PageContentFooter';
  21. import { CrowiRequest } from '~/interfaces/crowi-request';
  22. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  23. // import { useIndentSize } from '~/stores/editor';
  24. // import { useRendererSettings } from '~/stores/renderer';
  25. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  26. import { EditorConfig } from '~/interfaces/editor-settings';
  27. import { CustomWindow } from '~/interfaces/global';
  28. import { RendererConfig } from '~/interfaces/services/renderer';
  29. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  30. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  31. import { PageModel, PageDocument } from '~/server/models/page';
  32. import { PageRedirectModel } from '~/server/models/page-redirect';
  33. import UserUISettings from '~/server/models/user-ui-settings';
  34. import Xss from '~/services/xss';
  35. import { useSWRxCurrentPage, useSWRxPageInfo } from '~/stores/page';
  36. import {
  37. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  38. } from '~/stores/ui';
  39. import loggerFactory from '~/utils/logger';
  40. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  41. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  42. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  43. import ForbiddenPage from '../components/ForbiddenPage';
  44. import { BasicLayout } from '../components/Layout/BasicLayout';
  45. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  46. import { NotCreatablePage } from '../components/NotCreatablePage';
  47. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  48. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  49. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  50. import {
  51. useCurrentUser, useCurrentPagePath,
  52. useIsLatestRevision,
  53. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  54. useIsEnabledStaleNotification, useIsIdenticalPath,
  55. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  56. useHackmdUri,
  57. useIsAclEnabled, useIsUserPage, useIsNotCreatable,
  58. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  59. useIsSlackConfigured, useIsBlinkedHeaderAtBoot, useRendererConfig, useEditingMarkdown,
  60. useEditorConfig, useIsAllReplyShown,
  61. } from '../stores/context';
  62. import { useXss } from '../stores/xss';
  63. import {
  64. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  65. } from './utils/commons';
  66. // import { useCurrentPageSWR } from '../stores/page';
  67. const logger = loggerFactory('growi:pages:all');
  68. const {
  69. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage,
  70. } = pagePathUtils;
  71. const { removeHeadingSlash } = pathUtils;
  72. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  73. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  74. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  75. {
  76. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  77. return v?.data != null
  78. && v?.data.toObject != null
  79. && v?.meta != null
  80. && isIPageInfoForEntity(v.meta);
  81. },
  82. serialize: (v) => {
  83. return {
  84. data: superjson.stringify(v.data.toObject()),
  85. meta: superjson.stringify(v.meta),
  86. };
  87. },
  88. deserialize: (v) => {
  89. return {
  90. data: superjson.parse(v.data),
  91. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  92. };
  93. },
  94. },
  95. 'IPageToShowRevisionWithMetaTransformer',
  96. );
  97. const IdenticalPathPage = (): JSX.Element => {
  98. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  99. return <IdenticalPathPage />;
  100. };
  101. const PutbackPageModal = (): JSX.Element => {
  102. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  103. return <PutbackPageModal />;
  104. };
  105. type Props = CommonProps & {
  106. currentUser: IUser,
  107. pageWithMeta: IPageToShowRevisionWithMeta,
  108. // pageUser?: any,
  109. redirectFrom?: string;
  110. // shareLinkId?: string;
  111. isLatestRevision?: boolean
  112. isIdenticalPathPage?: boolean,
  113. isForbidden: boolean,
  114. isNotFound: boolean,
  115. IsNotCreatable: boolean,
  116. // isAbleToDeleteCompletely: boolean,
  117. isSearchServiceConfigured: boolean,
  118. isSearchServiceReachable: boolean,
  119. isSearchScopeChildrenAsDefault: boolean,
  120. isSlackConfigured: boolean,
  121. // isMailerSetup: boolean,
  122. isAclEnabled: boolean,
  123. // hasSlackConfig: boolean,
  124. // drawioUri: string,
  125. hackmdUri: string,
  126. // mathJax: string,
  127. // noCdn: string,
  128. // highlightJsStyle: string,
  129. isAllReplyShown: boolean,
  130. // isContainerFluid: boolean,
  131. editorConfig: EditorConfig,
  132. isEnabledStaleNotification: boolean,
  133. // isEnabledLinebreaks: boolean,
  134. // isEnabledLinebreaksInComments: boolean,
  135. // adminPreferredIndentSize: number,
  136. // isIndentSizeForced: boolean,
  137. disableLinkSharing: boolean,
  138. rendererConfig: RendererConfig,
  139. // UI
  140. userUISettings?: IUserUISettings
  141. // Sidebar
  142. sidebarConfig: ISidebarConfig,
  143. };
  144. const GrowiPage: NextPage<Props> = (props: Props) => {
  145. // const { t } = useTranslation();
  146. const router = useRouter();
  147. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  148. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  149. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  150. // register global EventEmitter
  151. if (isClient()) {
  152. (window as CustomWindow).globalEmitter = new EventEmitter();
  153. }
  154. // commons
  155. useXss(new Xss());
  156. useEditorConfig(props.editorConfig);
  157. useCsrfToken(props.csrfToken);
  158. // UserUISettings
  159. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  160. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  161. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  162. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  163. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  164. // page
  165. useCurrentPagePath(props.currentPathname);
  166. useIsLatestRevision(props.isLatestRevision);
  167. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  168. useIsForbidden(props.isForbidden);
  169. useIsNotFound(props.isNotFound);
  170. useIsNotCreatable(props.IsNotCreatable);
  171. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  172. // useShared();
  173. // useShareLinkId(props.shareLinkId);
  174. useIsSharedUser(false); // this page cann't be routed for '/share'
  175. useIsIdenticalPath(false); // TODO: need to initialize from props
  176. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  177. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  178. useIsBlinkedHeaderAtBoot(false);
  179. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  180. useIsSearchServiceReachable(props.isSearchServiceReachable);
  181. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  182. useIsSlackConfigured(props.isSlackConfigured);
  183. // useIsMailerSetup(props.isMailerSetup);
  184. useIsAclEnabled(props.isAclEnabled);
  185. // useHasSlackConfig(props.hasSlackConfig);
  186. // useDrawioUri(props.drawioUri);
  187. useHackmdUri(props.hackmdUri);
  188. // useMathJax(props.mathJax);
  189. // useNoCdn(props.noCdn);
  190. // useIndentSize(props.adminPreferredIndentSize);
  191. useDisableLinkSharing(props.disableLinkSharing);
  192. useRendererConfig(props.rendererConfig);
  193. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  194. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  195. useIsAllReplyShown(props.isAllReplyShown);
  196. // const { data: editorMode } = useEditorMode();
  197. const { pageWithMeta, userUISettings } = props;
  198. let shouldRenderPutbackPageModal = false;
  199. if (pageWithMeta != null) {
  200. shouldRenderPutbackPageModal = _isTrashPage(pageWithMeta.data.path);
  201. }
  202. useCurrentPageId(pageWithMeta?.data._id);
  203. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  204. // useSWRxPage(pageWithMeta?.data._id);
  205. useSWRxPageInfo(pageWithMeta?.data._id, undefined, pageWithMeta?.meta); // store initial data
  206. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  207. useIsUserPage(isUserPage(pageWithMeta?.data.path ?? ''));
  208. useIsNotCreatable(props.isForbidden || !isCreatablePage(pageWithMeta?.data.path ?? '')); // TODO: need to include props.isIdentical
  209. useCurrentPagePath(pageWithMeta?.data.path);
  210. useCurrentPathname(props.currentPathname);
  211. useEditingMarkdown(pageWithMeta?.data.revision.body);
  212. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  213. useEffect(() => {
  214. if (isClient() && window.location.pathname !== props.currentPathname) {
  215. router.replace(props.currentPathname, undefined, { shallow: true });
  216. }
  217. }, [props.currentPathname, router]);
  218. const classNames: string[] = [];
  219. // switch (editorMode) {
  220. // case EditorMode.Editor:
  221. // classNames.push('on-edit', 'builtin-editor');
  222. // break;
  223. // case EditorMode.HackMD:
  224. // classNames.push('on-edit', 'hackmd');
  225. // break;
  226. // }
  227. // if (props.isContainerFluid) {
  228. // classNames.push('growi-layout-fluid');
  229. // }
  230. // if (page == null) {
  231. // classNames.push('not-found-page');
  232. // }
  233. return (
  234. <>
  235. <Head>
  236. {/*
  237. {renderScriptTagByName('drawio-viewer')}
  238. {renderScriptTagByName('mathjax')}
  239. {renderScriptTagByName('highlight-addons')}
  240. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  241. */}
  242. </Head>
  243. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  244. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')}>
  245. <header className="py-0">
  246. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  247. </header>
  248. <div className="d-edit-none">
  249. <GrowiSubNavigationSwitcher />
  250. </div>
  251. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  252. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  253. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  254. <div id="content-main" className="content-main grw-container-convertible">
  255. <div className="row">
  256. <div className="col">
  257. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  258. { !props.isIdenticalPathPage && (
  259. <>
  260. <PageAlerts />
  261. { props.isForbidden && <ForbiddenPage /> }
  262. { props.IsNotCreatable && <NotCreatablePage />}
  263. { !props.isForbidden && !props.IsNotCreatable && <DisplaySwitcher />}
  264. {/* <DisplaySwitcher /> */}
  265. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  266. {/* <PageStatusAlert /> */}
  267. PageStatusAlert
  268. </>
  269. ) }
  270. </div>
  271. </div>
  272. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  273. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  274. <div id="revision-toc-content" className="revision-toc-content"></div>
  275. </div>
  276. </div> */}
  277. </div>
  278. </div>
  279. <footer>
  280. {/* <PageComments /> */}
  281. <PageComment isReadOnly={false} titleAlign="left" />
  282. <CommentEditorLazyRenderer />
  283. <PageContentFooter />
  284. </footer>
  285. <UnsavedAlertDialog />
  286. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  287. </BasicLayout>
  288. </>
  289. );
  290. };
  291. function getPageIdFromPathname(currentPathname: string): string | null {
  292. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  293. }
  294. class MultiplePagesHitsError extends ExtensibleCustomError {
  295. pagePath: string;
  296. constructor(pagePath: string) {
  297. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  298. this.pagePath = pagePath;
  299. }
  300. }
  301. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  302. const req: CrowiRequest = context.req as CrowiRequest;
  303. const { crowi } = req;
  304. const { revisionId } = req.query;
  305. const Page = crowi.model('Page') as PageModel;
  306. const PageRedirect = mongoose.model('PageRedirect') as PageRedirectModel;
  307. const { pageService } = crowi;
  308. let currentPathname = props.currentPathname;
  309. const pageId = getPageIdFromPathname(currentPathname);
  310. const isPermalink = _isPermalink(currentPathname);
  311. const { user } = req;
  312. if (!isPermalink) {
  313. // check redirects
  314. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  315. if (chains != null) {
  316. // overwrite currentPathname
  317. currentPathname = chains.end.toPath;
  318. props.currentPathname = currentPathname;
  319. // set redirectFrom
  320. props.redirectFrom = chains.start.fromPath;
  321. }
  322. // check whether the specified page path hits to multiple pages
  323. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  324. if (count > 1) {
  325. throw new MultiplePagesHitsError(currentPathname);
  326. }
  327. }
  328. const pageWithMeta: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  329. const page = pageWithMeta?.data as unknown as PageDocument;
  330. // populate & check if the revision is latest
  331. if (page != null) {
  332. page.initLatestRevisionField(revisionId);
  333. await page.populateDataToShowRevision();
  334. props.isLatestRevision = page.isLatestRevision();
  335. }
  336. props.pageWithMeta = pageWithMeta;
  337. }
  338. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  339. const req = context.req as CrowiRequest<IUserHasId & any>;
  340. const { user } = req;
  341. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  342. if (userUISettings != null) {
  343. props.userUISettings = userUISettings.toObject();
  344. }
  345. }
  346. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  347. const req: CrowiRequest = context.req as CrowiRequest;
  348. const { crowi } = req;
  349. const Page = crowi.model('Page') as PageModel;
  350. const { currentPathname } = props;
  351. const pageId = getPageIdFromPathname(currentPathname);
  352. const isPermalink = _isPermalink(currentPathname);
  353. const page = props.pageWithMeta?.data;
  354. if (props.isIdenticalPathPage) {
  355. // TBD
  356. }
  357. else if (page == null) {
  358. props.isNotFound = true;
  359. props.IsNotCreatable = !isCreatablePage(currentPathname);
  360. // check the page is forbidden or just does not exist.
  361. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  362. props.isForbidden = count > 0;
  363. }
  364. else {
  365. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  366. if (isPermalink && page.isEmpty) {
  367. props.currentPathname = page.path;
  368. }
  369. // /path/to/page ==> /62a88db47fed8b2d94f30000
  370. if (!isPermalink && !page.isEmpty) {
  371. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  372. if (!isToppage) {
  373. props.currentPathname = `/${page._id}`;
  374. }
  375. }
  376. }
  377. }
  378. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  379. // const req: CrowiRequest = context.req as CrowiRequest;
  380. // const { crowi } = req;
  381. // const UserModel = crowi.model('User');
  382. // if (isUserPage(props.currentPagePath)) {
  383. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  384. // if (user != null) {
  385. // props.pageUser = JSON.stringify(user.toObject());
  386. // }
  387. // }
  388. // }
  389. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  390. const req: CrowiRequest = context.req as CrowiRequest;
  391. const { crowi } = req;
  392. const {
  393. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  394. } = crowi;
  395. props.isSearchServiceConfigured = searchService.isConfigured;
  396. props.isSearchServiceReachable = searchService.isReachable;
  397. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  398. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  399. // props.isMailerSetup = mailService.isMailerSetup;
  400. props.isAclEnabled = aclService.isAclEnabled();
  401. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  402. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  403. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  404. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  405. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  406. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  407. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  408. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  409. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  410. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  411. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  412. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  413. props.editorConfig = {
  414. upload: {
  415. isImageUploaded: crowi.fileUploadService.getIsUploadable(),
  416. isFileUploaded: crowi.fileUploadService.getFileUploadEnabled(),
  417. },
  418. };
  419. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  420. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  421. props.rendererConfig = {
  422. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  423. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  424. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  425. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  426. plantumlUri: process.env.PLANTUML_URI ?? null,
  427. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  428. // XSS Options
  429. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  430. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  431. tagWhiteList: crowi.xssService.getTagWhiteList(),
  432. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  433. };
  434. props.sidebarConfig = {
  435. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  436. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  437. };
  438. }
  439. /**
  440. * for Server Side Translations
  441. * @param context
  442. * @param props
  443. * @param namespacesRequired
  444. */
  445. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  446. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  447. props._nextI18Next = nextI18NextConfig._nextI18Next;
  448. }
  449. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  450. const req = context.req as CrowiRequest<IUserHasId & any>;
  451. const { user } = req;
  452. const result = await getServerSideCommonProps(context);
  453. // check for presence
  454. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  455. if (!('props' in result)) {
  456. throw new Error('invalid getSSP result');
  457. }
  458. const props: Props = result.props as Props;
  459. if (user != null) {
  460. props.currentUser = user.toObject();
  461. }
  462. try {
  463. await injectPageData(context, props);
  464. }
  465. catch (err) {
  466. if (err instanceof MultiplePagesHitsError) {
  467. props.isIdenticalPathPage = true;
  468. }
  469. else {
  470. throw err;
  471. }
  472. }
  473. await injectUserUISettings(context, props);
  474. await injectRoutingInformation(context, props);
  475. injectServerConfigurations(context, props);
  476. await injectNextI18NextConfigurations(context, props, ['translation']);
  477. return {
  478. props,
  479. };
  480. };
  481. export default GrowiPage;